<template>
  <a-modal
    :title="title"
    :width="700"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="10">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="车位编号">
              <p style="font-size: 20px;font-weight: 500;margin: 0;text-align: center">{{ this.model.parkNumber }}</p>
            </a-form-item>
            <a-form-item v-show="false" :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否启用">
              <a-select v-decorator="['status', {initialValue:'Y'}]">
                <a-select-option :value="'Y'">启用</a-select-option>
                <a-select-option :value="'N'">冻结</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="有效期开始时间">
              <a-date-picker
                format="YYYY-MM-DD"
                :disabled="dataSource.length !== 0"
                v-decorator="[ 'startTime', {rules: [{ required: true, message: '请选择起始时间!' }],}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="有效期结束时间">
              <a-date-picker
                format="YYYY-MM-DD"
                :disabled="dataSource.length !== 0"
                v-decorator="[ 'endTime', {rules: [{ required: true, message: '请选择起始时间!' }],}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="租户姓名">
              <a-input
                placeholder="请输入租户姓名"
                :disabled="!(dataSource.length ===0 || isEdit === true)"
                v-decorator="['userName', {rules: [{ type: 'string', required: true, message: '请输入租户姓名!' },{max:40,message: '租户姓名长度不要超过40个字符'}]}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="租户手机号码">
              <a-input
                placeholder="请输入租户手机号码"
                :disabled="!(dataSource.length ===0 || isEdit === true)"
                v-decorator="['mobile', {rules: [{message: '请输入租户手机号'}]}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="租户家庭住址">
              <a-input
                placeholder="请输入家庭住址"
                :disabled="!(dataSource.length ===0 || isEdit === true)"
                v-decorator="['address', {rules:[{max:100,message:'家庭住址长度不要超过100个字符'}]}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="租金(元)">
              <a-input-number
                style="width: 100%"
                :min="0"
                :max="2100000000"
                :disabled="!(dataSource.length ===0 || isEdit === true)"
                v-decorator="[ 'payFee', {initialValue:0}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="车位备注">
              <a-textarea
                :auto-size="{ minRows: 6, maxRows: 6 }"
                :disabled="!(dataSource.length ===0 || isEdit === true)"
                v-decorator="['parkSpaceRemark',{}]">
              </a-textarea>
            </a-form-item>
          </a-col>
          <a-col :offset="2" :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="车牌号">
              <a-input
                placeholder="请输入车牌号"
                :disabled="isEdit"
                v-decorator="['plateNo', {rules: [{ type: 'string',required: !isEdit, message: '请输入车牌号!' }],}]"/>
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择车辆组类型">
              <a-select
                :options="carTypes"
                :disabled="isEdit===true"
                v-decorator="['carTypeId', {initialValue:defaultCarTypeId}]"
                placeholder="请选择月租车类型">
              </a-select>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="车辆备注">
              <a-input
                placeholder="请输入车辆备注"
                :disabled="isEdit===true"
                v-decorator="['remark', {rules:[{max:100,message:'车辆备注长度不要超过100个字符'}]}]"/>
            </a-form-item>
            <a-row style="line-height: 40px;margin-bottom: 24px">
              <a-col :span="24" align="center">
                <a-row>
                  <a-button :disabled="isEdit===true" style="width: 100%" type="primary" @click="handleBindPlateNo">
                    添加
                  </a-button>
                </a-row>
                <a-row>
                  <a-button :disabled="dataSource.length===0" style="width: 100%" type="primary" @click="handleEdit">
                    {{ editBtnMessage }}
                  </a-button>
                </a-row>
              </a-col>
            </a-row>
            <a-row style="height: 343px">
              <a-table
                size="small"
                bordered
                rowKey="id"
                :columns="columns"
                :dataSource="dataSource"
                :loading="confirmLoading"
                :pagination="false"
                :defaultExpandAllRows="true"
                style="word-break: break-all">
                <span slot="carTypeId" slot-scope="text,record">
                  {{ carTypeIdTranslate(text) }}
                </span>
                <span slot="action" slot-scope="text, record">
                  <a-popconfirm v-show="record.id" title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </span>
              </a-table>
            </a-row>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        返回
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from "lodash.pick";
import moment from "moment";
import {deleteAction, getAction, httpAction, postAction} from '@api/manage'

export default {
  name: "ParkingSpaceEditModal",
  data() {
    return {
      form: this.$form.createForm(this),
      title: '',
      visible: false,
      confirmLoading: false,
      model: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 12},
        style: 'textAlign: left',
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
      },

      // 表头
      columns: [
        {
          title: '车牌号',
          dataIndex: 'plateNo',
          width: 80,
          align: "center"
        },
        {
          title: '车辆类型',
          dataIndex: 'carTypeId',
          width: 80,
          align: 'center',
          ellipsis:true,
          scopedSlots: {customRender: 'carTypeId'}
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 80,
          ellipsis:true,
          align: "center"
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'},
          width: 40
        }
      ],
      dataSource: [],
      carTypes: [],
      selectCarTypeId:'',
      defaultCarTypeId: '',
      url: {
        queryCarList: '/parkCar/parkNumber/queryCarList',
        carTypeList: "/ConfigCarType/configCarType/parkCarTypeList",
        edit:'/parkCar/parkNumber/edit',
        bindPlateNO: '/parkCar/parkNumber/bindPlateNo',
        delete: "/parkCar/parkNumber/removeBindCar",
      },
      isEdit:false,
      editBtnMessage:'修改车位信息'
    }
  },
  methods: {
    edit(record) {
      const that = this
      this.visible = true;
      this.confirmLoading = true
      this.isEdit = false;
      this.form.resetFields();
      this.model = Object.assign(this.model, record);
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'status', 'userName', 'mobile', 'address', 'payFee','parkSpaceRemark'))
        this.form.setFieldsValue({startTime: this.model.startTime ? moment(this.model.startTime) : null})
        this.form.setFieldsValue({endTime: this.model.endTime ? moment(this.model.endTime) : null})
        that.loadParkCarType()
        that.loadParkNumberData()
      });
    },
    carTypeIdTranslate(id){
      let result = ''
      this.carTypes.forEach(cars=>{
        if(cars.value===id)
        {
          return result = cars.label
        }
      })
      return result
    },
    handleDelete(id) {
      this.confirmLoading = true
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadParkNumberData();

        } else {
          that.$message.warning(res.message);
        }
      });
    },
    handleBindPlateNo() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let formData = Object.assign(this.model, values);
          this.confirmLoading = true
          formData.startTime = formData.startTime ? formData.startTime.format('YYYY-MM-DD 00:00:00') : null;
          formData.endTime = formData.endTime ? formData.endTime.format('YYYY-MM-DD 00:00:00') : null;
          httpAction(that.url.bindPlateNO, {
            parkSpaceRemark: that.form.getFieldValue("parkSpaceRemark"),
            parkCarMonthly: formData
          }, 'post').then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.loadParkNumberData();
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleEdit() {
      if(this.isEdit===false){
        this.isEdit =true;
        this.selectCarTypeId = this.form.getFieldValue("carTypeId")
        this.editBtnMessage = "确定"
      }else {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            let formData = {}
            formData.id = that.model.id
            formData.userName = values.userName
            formData.mobile = values.mobile
            formData.address = values.address
            formData.payFee = values.payFee
            formData.remark = values.remark
            this.confirmLoading = true
            httpAction(that.url.edit, formData, 'post').then((res) => {
              if (res.success) {
                that.$message.success(res.message);
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        })

        this.isEdit = false
        this.form.setFieldsValue({carTypeId:this.selectCarTypeId})
        this.editBtnMessage = "编辑车位信息"
      }
    },
    loadParkNumberData() {
      const that = this
      let params = {}
      params.parkCode = this.model.parkCode
      params.parkNumber = this.model.parkNumber
      postAction(this.url.queryCarList, params).then(res => {
        if (res.success) {
          that.dataSource = res.result
          if (that.dataSource.length === 0) {
            that.resetForm();
          }
          that.form.setFieldsValue({plateNo: null})
          that.form.setFieldsValue({carTypeId: that.defaultCarTypeId})
          that.form.setFieldsValue({remark: null})
        }
        that.confirmLoading = false
      })
    },
    async loadParkCarType() {
      let params = []
      const that = this
      params.method = 'monthCar'
      await getAction(this.url.carTypeList, params).then((res) => {
        if (res.success && res.result.length > 0) {
          const CarArray = []
          res.result.forEach((car) => {
            CarArray.push({
              value: car.id,
              label: car.carTypeName
            })
          })
          that.defaultCarTypeId = CarArray[0].value
          that.form.setFieldsValue({carTypeId:that.defaultCarTypeId})
          that.selectCarTypeId = that.defaultCarTypeId
          that.carTypes = CarArray
        }
      })
    },
    resetForm() {
      this.form.resetFields();
      this.form.setFieldsValue({startTime: null})
      this.form.setFieldsValue({endTime: null})
      this.form.setFieldsValue({userName: null})
      this.form.setFieldsValue({mobile: null})
      this.form.setFieldsValue({address: null})
      this.form.setFieldsValue({remark: null})
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('ok');
      this.isEdit = false;
      this.visible = false;
      this.dataSource = []
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback();
      } else {
        callback("手机号码格式不正确!");
      }
    }
  }
}
</script>

<style scoped>

</style>
